import MySQLdb
import Image, ImageDraw, ImageFilter, ImageFont
import sys
import gtk
clipboard = gtk.clipboard_get()

def show():
	conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='defcon')

	#  Generate the map
	im = Image.new('RGBA', (1000, 1000), '#000000')
	draw = ImageDraw.Draw(im)

	# Set styles
	colors = ['#F00', '#0F0', '#00F', '#0FF', '#F0F', '#FF0', '#600', '#060', '#006', '#066', '#606', '#660']
	font = font = ImageFont.truetype("Molengo-Regular.ttf", 15)

	# Draw the grid
	for x in range(10):
		draw.rectangle([(x*100, 0), (x*100, 1000)], '#333')
		draw.text((x*100+45, 2), str(x), fill='#999', font=font)
		draw.text((x*100+45, 980), str(x), fill='#999', font=font)
	for y in range(10):
		draw.rectangle([(0, y*100), (1000, y*100)], '#333')
		draw.text((2, y*100+40), str(y), fill='#999', font=font)
		draw.text((990, y*100+40), str(y), fill='#999', font=font)

	# Get the top 12 alliances
	sql = 'SELECT id, name, points, members, rank from alliances ORDER BY rank LIMIT 12';
	conn.query(sql)
	allies = conn.store_result().fetch_row(maxrows=0)
	
	allies = [
		['168', 'The Heirs of Artemis'],
		['32', 'IX Legion']
	]
	
	alliances = []
	ty = 750
	draw.rectangle([(0, 750), (170, 1000)], '#111')
	for ally in allies:
		alliances.append(str(ally[0]))
		colorid = alliances.index(str(ally[0]))
		draw.text((10, ty), ally[1].replace('+', ' '), fill=colors[colorid], font=font)
		ty = ty + 20

	# Get the towns from top 12 alliances
	sql = """
		SELECT
			t.name, t.points, p.alliance_id, t.island_x, t.island_y
		FROM
			towns t LEFT JOIN players p ON t.player_id = p.id
		GROUP BY
			t.island_x, t.island_y
		ORDER BY
			t.points DESC
	"""
	conn.query(sql)
	towns = conn.store_result().fetch_row(maxrows=0)

	for town in towns:
		# Get the towns in the island
		ix = town[3]; iy = town[4]
		try:
			colorid = alliances.index(str(town[2]))
			color = colors[colorid]
		except:
			color = '#333'
		draw.rectangle([(ix-1, iy-1), (ix+1, iy+1)], color)

	im.show()

	saveit = raw_input('Save it? y/n.')
	if saveit == 'y' or saveit == 'Y' or saveit == 'yes':
		im.save('/home/bruno/Dropbox/Public/games/grepolis/world-alliances.png')
		clipboard.set_text('http://dl.dropbox.com/u/121630/games/grepolis/world-alliances.png')
		print 'http://dl.dropbox.com/u/121630/games/grepolis/world-alliances.png'
		print 'Public URL on the clipboard'

if __name__ == "__main__":
    show()
